import React, { useMemo, useState, useCallback } from "react";
import { useRequest } from "ahooks";
import {
  Table,
  Button,
  Form,
  Input,
  Radio,
  Select,
  Divider,
  message,
  Image,
  Tag,
} from "antd";
import { getProSearchListApi, getProCategoriesApi } from "@/api/pro";
import AppDrawerViewEdit, { useDetailDrawer } from "../AppDrawerViewEdit/index";
import Authority from "@/compnents/Authority";
export default function AppProList() {
  const [form] = Form.useForm();
  const { open, toggleOpen, proid, handeCheck } = useDetailDrawer();
  // 使用useRequest调取接口getProListApi
  const {
    data,
    loading,
    run: getDataList,
  } = useRequest((params = { search: "", category: "" }) =>
    getProSearchListApi(params)
  );
  const { data: categories = [] } = useRequest(getProCategoriesApi);
  console.log("过来的数据", open, data);
  // 打开抽屉弹窗的逻辑

  const categoriesOptions = useMemo(
    () => categories.map((item) => ({ value: item, label: item, title: item })),
    [categories]
  );
  const columnsThis = [
    {
      title: "商品名称",
      dataIndex: "proname",
      key: "proname",
      ellipsis: true,
      width: 200,
      align: "center",
      editable: true,
    },
    {
      title: "图片",
      dataIndex: "img1",
      key: "img1",
      width: 150,
      align: "center",
      render: (text) => <Image width={100} src={text} />,
    },
    {
      title: "品牌",
      dataIndex: "brand",
      key: "brand",
      render: (text) => (
        <Tag color="cyan">
          <a href="#"> {text} </a>{" "}
        </Tag>
      ),
      align: "center",
    },
    {
      title: "专享价格",
      dataIndex: "originprice",
      key: "originprice",
      width: 120,
      align: "center",
      render: (text) => <h1 style={{ color: "red" }}> {text} </h1>,
    },
    {
      title: "已售数量",
      dataIndex: "sales",
      key: "sales",
      align: "center",
    },
    {
      title: "操作",
      width: 200,
      render: (_, record) => (
        <Authority mode="disabled" judge={(role) => role > 1}>
          <Button type="default" onClick={() => handeCheck(record.proid)}>
            查看
          </Button>
        </Authority>
      ),
    },
  ];
  // const columnsThis = useMemo(() => columns, []);
  const [formLayout, setFormLayout] = useState("inline");
  const onFormLayoutChange = ({ layout }) => {
    setFormLayout(layout);
  };
  const formItemLayout =
    formLayout === "horizontal"
      ? {
          labelCol: {
            span: 4,
          },
          wrapperCol: {
            span: 14,
          },
        }
      : null;
  const buttonItemLayout =
    formLayout === "horizontal"
      ? {
          wrapperCol: {
            span: 14,
            offset: 4,
          },
        }
      : null;
  // 查询
  const handleSubmit = useCallback(async () => {
    // let flag =
    let flag = await form.validateFields().catch((errorInfo) => {
      if (errorInfo) {
        console.log("dwadwa", errorInfo);
        message.error("查询条件错误，请检查重试");
        return false;
      }
    });

    if (!flag) {
      return;
    }
    console.log("dwadwa", flag);
    const values = form.getFieldsValue();
    console.log("表单值", values);
    // values.category = values.category === undefined ? "" : values.category;
    Object.keys(values).forEach((keys) => {
      if (values[keys] === undefined) values[keys] = "";
    });
    getDataList(values);
  }, [form]);

  return (
    <>
      <Form
        {...formItemLayout}
        layout={formLayout}
        form={form}
        initialValues={{
          layout: formLayout,
        }}
        onValuesChange={onFormLayoutChange}
      >
        <Form.Item label="表单布局" name="layout">
          <Radio.Group value={formLayout}>
            <Radio.Button value="horizontal">常规</Radio.Button>
            <Radio.Button value="vertical">巨大</Radio.Button>
            <Radio.Button value="inline">行内</Radio.Button>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          name="category"
          label="分类"
          validateTrigger="onBlur"
          initialValue=""
        >
          <Select
            allowClear="true"
            showSearch
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label ?? "").includes(input)
            }
            filterSort={(optionA, optionB) =>
              (optionA?.label ?? "")
                .toLowerCase()
                .localeCompare((optionB?.label ?? "").toLowerCase())
            }
            placeholder="请选择分类"
            style={{
              width: 140,
            }}
            options={categoriesOptions}
          />
        </Form.Item>
        <Form.Item
          name="search"
          validateTrigger="onBlur"
          label="搜索"
          initialValue=""
          rules={[{ max: 5, message: "最多5个字符！" }]}
        >
          <Input
            style={{
              width: 140,
            }}
            placeholder="请输入查询条件"
          />
        </Form.Item>
        <Form.Item {...buttonItemLayout}>
          <Button type="primary" onClick={handleSubmit}>
            查询
          </Button>
        </Form.Item>
      </Form>
      <Divider></Divider>
      <Button type="primary" onClick={() => handeCheck("")}>
        新增
      </Button>
      <Divider></Divider>
      <AppDrawerViewEdit open={open} toggleOpen={toggleOpen} proid={proid} />
      <Table
        loading={loading}
        dataSource={data ? data : []}
        rowKey="proid"
        columns={columnsThis}
      />
    </>
  );
}
